<?php

namespace common\service;

use common\exception\LogicException;
use common\model\EntityModel;
use common\model\TaskModel;
use support\ErrorCode;
use support\SingletonTrait;
use think\Exception;

class StoryboardService
{
    use SingletonTrait;


    /**
     * 关联资产贴图
     * @param array $storyboardIdList
     * @param int $entityId
     * @param int $todoTaskId
     * @return array
     * @throws \think\Exception
     */
    public function relateTodoTask(array $storyboardIdList, int $entityId, int $todoTaskId)
    {
        $res = [];
        $queryFields = [
            'id',
            'storyboard_asset',
            'storyboard_level',
            'storyboard_task',
        ];
        $storyboardList = model(EntityModel::class)
            ->alias('storyboard')
            ->where(['id' => ['IN', $storyboardIdList]])
            ->field(transform_custom_fields($queryFields, 'storyboard'))
            ->select();

        if (empty($storyboardList)) {
            throw new LogicException('entity not found', ErrorCode::ENTITY_NOT_FOUND);
        }

        $entity = model(EntityModel::class)->where(['id' => $entityId])->field('id,module_id,json')->find();
        $designId = json_decode($entity['json'], true)[module_by_id($entity['module_id'])['code'] . '_design'] ?? 0;
        if (empty($designId)) {
            return $res;
        }
        $beRelatedEntityTodoTaskListFilter = [
            'entity_id' => $designId,
            'entity_module_id' => module_by_code('todo')['id'],
            'step_type' => TaskModel::STEP_TYPE_ENTITY_TO_DO,
        ];
        $beRelatedEntityTodoTaskIdList = model(TaskModel::class)->where($beRelatedEntityTodoTaskListFilter)->column('id');

        $storyboardCommonService = CommonService::instance('entity');
        $storyboardCommonService->setCurrentModuleCode('storyboard');
        $AsyncCallService = AsyncCallService::getInstance();
        if ($todoTaskId > 0) {
            if (!in_array($todoTaskId, $beRelatedEntityTodoTaskIdList)) {
                throw new LogicException(" todo_task_id data invalid", ErrorCode::DATA_INVALID);
            }
            // 增加贴图关联
            foreach ($storyboardList as $storyboard) {
                if (!empty($storyboard['storyboard_task'])) {
                    $storyboard['storyboard_task_explode'] = array_filter(explode(',', $storyboard['storyboard_task']), function ($item) use ($todoTaskId, $beRelatedEntityTodoTaskIdList) {
                        return !empty($item) && !in_array($item, $beRelatedEntityTodoTaskIdList);
                    });
                } else {
                    $storyboard['storyboard_task_explode'] = [];
                }
                if (!in_array($todoTaskId, $storyboard['storyboard_task_explode'])) {
                    $storyboard['storyboard_task_explode'][] = $todoTaskId;
                    $res[] = $storyboardCommonService->update(['id' => $storyboard['id'], 'storyboard_task' => implode(',', $storyboard['storyboard_task_explode'])]);
                    $AsyncCallService->syncRelationDataAsync($storyboard['id'], 'storyboard');
                }
            }
        } else {
            // 移除贴图关联
            $oldTaskIdList = [];
            foreach ($storyboardList as $storyboard) {
                if (!empty($storyboard['storyboard_task'])) {
                    foreach (array_filter(explode(',', $storyboard['storyboard_task'])) as $taskId) {
                        $oldTaskIdList[$taskId] = $taskId;
                    }
                }
            }
            if (empty($oldTaskIdList)) {
                return $res;
            }

            $oldTaskFilter = [
                'id' => ['IN', array_values($oldTaskIdList)],
                'entity_id' => $designId,
                'entity_module_id' => module_by_code('todo')['id'],
                'step_type' => TaskModel::STEP_TYPE_ENTITY_TO_DO,
            ];
            $entityTodoTaskIdList = model(TaskModel::class)->where($oldTaskFilter)->column('id');

            foreach ($storyboardList as $storyboard) {
                if (!empty($storyboard['storyboard_task'])) {
                    $storyboard['storyboard_task_explode'] = array_filter(explode(',', $storyboard['storyboard_task']));
                    $intersect = array_intersect($entityTodoTaskIdList, $storyboard['storyboard_task_explode']);
                    if (!empty($intersect)) {
                        $storyboard['storyboard_task_explode'] = array_filter($storyboard['storyboard_task_explode'], function ($item) use ($intersect) {
                            return !in_array($item, $intersect);
                        });
                        $res[] = $storyboardCommonService->update(['id' => $storyboard['id'], 'storyboard_task' => implode(',', $storyboard['storyboard_task_explode'])]);
                        $AsyncCallService->syncRelationDataAsync($storyboard['id'], 'storyboard');
                    }
                }
            }
        }
        return $res;
    }
}
